package com.example.service;

import com.example.client.ProductClient;
import com.example.common.Result;
import com.example.entity.CartItem;
import com.example.entity.Product;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class CartService {
    private final Map<Long, List<CartItem>> userCartMap = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong();
    private final ProductClient productClient;

    public CartService(ProductClient productClient) {
        this.productClient = productClient;
    }

    public CartItem addToCart(Long userId, Long productId, Integer quantity) {
        Result<Product> productResult = productClient.getProductById(productId);
        if (productResult.getCode() == 200 && productResult.getData() != null) {
            Product product = productResult.getData();
            CartItem cartItem = new CartItem();
            cartItem.setId(idGenerator.incrementAndGet());
            cartItem.setUserId(userId);
            cartItem.setProductId(productId);
            cartItem.setQuantity(quantity);
            cartItem.setPrice(product.getPrice());

            userCartMap.computeIfAbsent(userId, k -> new ArrayList<>()).add(cartItem);
            return cartItem;
        }
        return null;
    }

    public List<CartItem> getUserCart(Long userId) {
        return userCartMap.getOrDefault(userId, new ArrayList<>());
    }

    public boolean checkout(Long userId) {
        List<CartItem> cartItems = userCartMap.get(userId);
        if (cartItems != null && !cartItems.isEmpty()) {
            for (CartItem item : cartItems) {
                Result<Boolean> result = productClient.updateStock(item.getProductId(), item.getQuantity());
                if (result.getCode() != 200 || !result.getData()) {
                    return false;
                }
            }
            userCartMap.remove(userId);
            return true;
        }
        return false;
    }
} 